<template>
  <a-drawer
    title="新增物资入库"
    :maskClosable="false"
    width=80%
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="budgetAddVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form="form" layout="horizontal">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='单据日期'
                       v-bind="formItemLayout"
                       :help="help">
            <vue-datepicker-local v-model="billDate" format="YYYY-MM-DD" style="display: block"></vue-datepicker-local>
          </a-form-item>
        </a-col>

        <a-col :md="12" :sm="24">
          <a-form-item label='保管员'
                       v-bind="formItemLayout">
            <a-input v-model="storeKeeper"
                     v-decorator="['storeKeeper',{rules: [{ required: true, message: '厂家不能为空'}]}]"/>
          </a-form-item>
        </a-col>
<!--        <a-col :md="12" :sm="24">
          <a-form-item label='仓库列表' v-bind="formItemLayout">
            <a-select
              :allowClear="true"
              :dropdownStyle="{ maxHeight: '220px', overflow: 'auto' }"
              v-decorator="['storeCode',{rules: [{ required: true, whitespace: true, message: '仓库名称不能为空', }]}]"
              >
            <a-select-option v-for="r in storeTreeData" :key="r.id">{{r.storeName}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>-->
      </a-row>
    </a-form>
    <a-row>
      <div>
        <a-tabs defaultActiveKey="1">
          <a-tab-pane tab="入库详情" key="1">
            <a-button @click="newMember" type="primary" icon="plus" style="margin-bottom:8px">新增入库</a-button>
            <a-table
              ref="table"
              size="middle"
              bordered
              rowKey="id"
              :columns="columns"
              :dataSource="dataSource">
              <template v-for="(col,i) in ['materialCode','materialsId','spe','unit','mnumber','price','amount','remarks']" :slot="col" slot-scope="text, record, index">
                <a-input
                  readOnly
                  :key="col"
                  v-if=" col=='materialCode' "
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).materialCode"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  readOnly
                  :key="col"
                  v-if=" col=='spe' "
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).spe"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  readOnly
                  :key="col"
                  v-if=" col=='unit' "
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).unit"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  :key="col"
                  v-if="col=='remarks' || col=='price' || col =='mnumber'"
                  style="margin: -5px 0"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <a-input
                  readOnly
                  :key="col"
                  v-if=" col=='amount' "
                  style="margin: -5px 0"
                  :value="gteDataSourceData(record.key).price*gteDataSourceData(record.key).mnumber"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />

                <a-select v-if="col=='materialsId'" style="width: 120px"  @change="value => handleChange(value, record.key, col)">
                  <a-select-option v-for="(option, index) in projectList " :key="index" :value="option.id">{{option.materialName}}</a-select-option>
                </a-select>
              </template>


            </a-table>

          </a-tab-pane>
        </a-tabs>
      </div>
    </a-row>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">保存</a-button>
    </div>
  </a-drawer>
</template>
<script>
  import VueDatepickerLocal from 'vue-datepicker-local'
  import moment from 'moment'

  const formItemLayout = {
    labelCol: {span: 4},
    wrapperCol: {span: 15, offset: 2}
  }

  export default {
    name: 'annualBudgetGetAdd',
    components: {VueDatepickerLocal},
    props: {
      budgetAddVisiable: {
        default: false
      }
    },
    data () {
      return {
        storeKeeper:'',
        supper:'',
        billDate:moment(new Date()).format('YYYY-MM-DD'),
        budGetYear: '',
        dataSource: [],
        loading: false,
        deptTreeData: [],
        storeTreeData:[],
        budgetInfotList:[],
        treeData: [],
        planTypeTreeData:[],
        typeTree: [],
        deptId: '',
        storeCode:'',
        typeValue: '',
        projectList: [],
        selectedRowKeys: [],
        iExpandedKeys: [],
        form: this.$form.createForm(this),
        validateStatus: '',
        help: '',
        pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
        },
        formItemLayout: {
          labelCol: {
            xs: {span: 24},
            sm: {span: 4},
          },
          wrapperCol: {
            xs: {span: 24},
            sm: {span: 20},
          },
        },

        newMemberData:{
          key: '',
          materialCode: '',
          materialsId:'',
          spe: '',
          unit:'',
          mnumber:'',
          price:'',
          amount:'',
          remarks: ''
        },
      }
    },
    computed: {
      columns () {
        let {sortedInfo, filteredInfo} = this
        sortedInfo = sortedInfo || {}
        filteredInfo = filteredInfo || {}
        return [{
          title: '序号',
          width: 80,
          customRender: function (text, record, index) {
            return index + 1
          }
        },{
          title: '材料编码',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' }
        }, {
          title: '物资类别',
          dataIndex: 'materialsId',
          scopedSlots: { customRender: 'materialsId' }
        }, {
          title: '材料规格',
          dataIndex: 'spe',
          scopedSlots: { customRender: 'spe' }
        }, {
          title: '单位',
          dataIndex: 'unit',
          scopedSlots: { customRender: 'unit' }
        }, {
          title: '单价',
          dataIndex: 'price',
          scopedSlots: { customRender: 'price' }
      }, {
          title: '数量',
          dataIndex: 'mnumber',
          scopedSlots: { customRender: 'mnumber' }
        }, {
          title: '金额',
          dataIndex: 'amount',
          scopedSlots: { customRender: 'amount' }
        }, {
          title: '备注',
          dataIndex: 'remarks',
          scopedSlots: { customRender: 'remarks' }
        }
        ]
      }
    },
    mounted () {
      this.loadTreeData();

    },
    beforeCreate () {
      this.budgetForm = this.$form.createForm(this)
      this.budgetForm.getFieldDecorator('keys', {initialValue: [], preserve: true})
    },
    methods: {
      moment,
      newMember () {
        this.form.validateFields((err, values) => {
            if(!err){
              this.newMemberData={
                key: '',
                materialCode: '',
                materialsId:'',
                spe: '',
                unit:'',
                mnumber:'',
                price:'',
                amount:'',
                remarks: ''
              }
              this.newMemberData.key=Math.random().toString(36).substring(2);
              this.dataSource.push(this.newMemberData)
            }
        })

      },
      handleChange (value, key, column) {
        const newData = [...this.dataSource]
        const target = newData.filter(item => key === item.key)[0]

        if(column.trim()=='materialsId'){
          this.$get("materialsInfo/getOne",{"bid":value}).then((res)=>{
            if (target) {
              target['materialCode'] = res.data.materialCode;
              target['spe'] = res.data.spec;
              target['unit'] = res.data.unit;
              this.dataSource = newData
            }
          })
        }
        if (target) {
          target[column] = value
          this.dataSource = newData
        }
      },
      gteDataSourceData(key){
        const newData = [...this.dataSource]
        const target = newData.filter(item => key === item.key)[0];
        if(target){
          return target;
        }
        return {};
      },

      loadProjectSelect () {
        this.$get("materialsInfo",{"type_id":this.typeId}).then((res) => {
          this.projectList=res.data.data;
        })
      },
      onDeptChange (value, lable, extra) {
        this.maindeptName=lable;
        this.deptId=value;
        this.$get('dept/getOne', {'deptId': value}).then((res) => {
       //   this.newMemberData.billDate=moment(this.billDate).format('YYYY-MM-DD');
        //  this.newMemberData.deptCode=res.data.deptCode;
          this.deptCode=res.data.deptCode;
         // this.newMemberData.deptId=value
        })
        //this.loadProjectSelect();
        this.deptId = value
      },
      onTypeChange (value, lable, extra) {
        this.mainTypeName=lable;
        this.typeId=value;
        debugger;
        this.$get('materialsType/getOne', {'typeId': value}).then((res) => {

          // this.newMemberData.materialCode=res.data.typeCode;
          this.typeName=res.data.typeName;
          //this.newMemberData.typeId=value
        })
        this.loadProjectSelect();
        this.typeId = value
      },
      loadTreeData () {
        let that = this
        that.$get('projectType').then((res) => {
          for (let i = 0; i < res.data.rows.children.length; i++) {
            let temp = res.data.rows.children[i]
            that.setThisExpandedKeys(temp)
          }
          that.treeData = res.data.rows.children
          that.typeTree = res.data.rows.children
        })
      }, setThisExpandedKeys (node) {
        if (node.children && node.children.length > 0) {
          this.iExpandedKeys.push(node.key)
          for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
        }
      },
      reset () {
        this.validateStatus = ''
        this.help = ''
        this.projectName = ''
        this.loading = false
        this.form.resetFields()
      },
      onClose () {
        this.dataSource=[];
        this.form.resetFields();
        this.reset()
        this.$emit('close')
      },
      handleSubmit () {
        this.form.validateFields((err, values) => {
          if (!err) {
            values.deptName=this.maindeptName[0];
            values.typeName=this.mainTypeName[0];
            values.deptCode=this.deptCode;

            values.billDate=moment(this.billDate).format('YYYY-MM-DD');
           this.dataSource.forEach(item=>{
              item.amount=item.price*item.mnumber;

            });

            this.$post("materialIn/addMaterialIn",{"materialIn":JSON.stringify(values),"listdetail":JSON.stringify(this.dataSource)}).then((res)=>{
              if(res.data.code==200){
                this.dataSource=[];
                this.form.resetFields();
                this.$emit("success");
              }else{
                this.$message.info("新增失败")
              }
            })
          }
        })
      },
    },
    //监控值的改变
    watch: {
      budgetAddVisiable () {
        if (this.budgetAddVisiable) {
          this.$get('annualBudget/dept').then((r) => {
            this.deptTreeData = r.data.rows.children
          })
          this.$get('materialPlan/type').then((r) => {
            this.planTypeTreeData = r.data.rows.children
          })
          this.$get('storehouse/getStoreByName').then((r) => {
            this.storeTreeData = r.data.rows
          })
        }
      }
    }
  }
</script>

<style>

</style>
